﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.Transactions;
using System.Collections ;

namespace MaxLeaf.DAL.K3
{
    public class OeSalesOrderDAL 
    {

        //特别注意****************************************************
        //在网站的数据库填的都是  K3 主帐套的 FItemID , 如果找不到，就应该
        //用fitemid找出主账套fnumber  再用fnumber到对应的K3分帐套支找。
        //************************************************************

        //备注： 是不是能通过 mary_order_info 中的mdc_ID 来获得region_dbName
        //SELECT * FROM  `mary_order_info`  A inner join mary_mdc B on A.mdc_id=B.id;
        //
        //同样由K3向网站写的时候，我们也可以用 FinterID + 数据库名称来判断是不是写到哪个网站数据库。

        //*****************************************************************************
        //select  ftypeid, * from  t_organization  where fnumber='1.11.001.001'
        //select  finterid, * from  t_SubMessage where ftypeid=501 and finterid=40001
        //这两个表的关系是： t_organization.ftypeid=t_SubMessage.finterid
        //*****************************************************************************

        //--导入销售单
        //geticbillno  -- 获得新的BillNo
        //getmaxnum --Finter

        public string mstrOEHDR_Web = "mary_order_info";
        public string mstrOEHDR_K3 = "SEOrder";
        public string mstrOEDTL_Web = "mary_order_goods";
        public string mstrOEDTL_K3 = "SEOrderEntry";
        //,fheadselfS0144
        //FHeadSelfS0168 单据产生的日期
        public string mstrFieldNamesHDR_K3 = @" FBrNo,finterid,fbillno,Fcurrencyid,FcustID,Fdate,FsaleStyle,FdeptID,FEmpID,Fcheckerid,fbillerid
                                                ,Ftrantype,finvoiceclosed,fbclosed,fmangerid,fsettleid,fexchangerate,fdiscounttype,fstatus,fcancellation
                                                ,Fcheckdate,Fsettledate,fseltrantype,fchildren,fbrid,fareaps,fsysstatus                                                
                                                ,fheadselfS0160,fheadselfS0161,fheadselfS0162,FHeadSelfS0150
                                                ,fheadselfS0163,fheadselfS0164,fheadselfS0165,fheadselfS0166,fheadselfS0167,FHeadSelfS0168,FHeadSelfS0157";

        public string mstrFieldNamesDTL_K3 = @"FBrNO,FInterID,FEntryID,FItemID,FQty,FCommitQty,FPrice,FAmount,FTaxRate,FTaxAmount,FTax,FDiscount,FNote,FDate,
                                                FDiscountAmount,FInvoiceQty,FBCommitQty,FTranLeadTime,FATPDeduct,FCostObjectID,FUnitID,FAuxPrice,FAuxQty,FCESS,
                                                FAllAmount,FAllStdAmount,FAuxPriceDiscount,FPriceDiscount,FTaxAmt,FAuxTaxPrice,FTaxPrice,FDetailID,FMrpAutoClosed,
                                                FSecStockQty,FSecInvoiceQty,FSecCommitInstall,FPlanMode,FEntrySelfS0161,FEntrySelfS0162,FEntrySelfS0163,
                                                FEntrySelfS0168,FEntrySelfS0171,FAdviceConsignDate,FStockQty,FAuxStockQty,FMrpClosed";

        public string mstrFieldNamesHDR_Web = "";
        public string mstrFieldNamesDTL_Web = "rec_id,order_id,FItemID,goods_id,goods_name,goods_sn,goods_number,goods_unit,market_price,goods_price,send_number,goods_color,k3stockbillfinterid";
        public struct OrderInfo
        {
            public string ServerName;
            public string DBName;
            public string BillNo_Web  ;
            public string BillNo_K3  ;
            public string FInterID;
            public string CustID;
            public DateTime FDate;
            public string CustTypeID;   //t_organization中的TypeID,和物料的FItemID一起决定，从icprcplyentry中取价格
            //public OrderDetail[] Detail;
            public List<OrderDetail> Detail; 
        }
        public struct OrderDetail
        {
            /// <summary>
            /// 内部单号
            /// </summary>
            public string FInterID ;
            
            /// <summary>
            /// 行号
            /// </summary>
            public string FEntryID;
            
            /// <summary>
            /// 物料ID
            /// </summary>
            public string FItemID;
            
            /// <summary>
            /// 物料类型ID，存在于t_icitem中，用于表示属于哪个类型，从而决定这个物料的折扣，价格表：icdisplyentry
            /// </summary>
            public string FItemTypeID;    // 物料类型ID，存在于t_icitem中，用于表示属于哪个类型，从而决定这个物料的折扣，价格表：icdisplyentry
            
            /// <summary>
            /// 基本单位的数量
            /// </summary>
            public double FBaseQty;
            
            /// <summary>
            /// 销售记量单位    
            /// </summary>
            public string FAuxUnitID;      //销售记量单位    

            /// <summary>
            /// 销售记量单位的价格
            /// </summary>
            public double FAuxPrice;       //销售记量单位的价格
            
            /// <summary>
            /// 销售记量单位的数量
            /// </summary>
            public double FAuxQty;       //销售记量单位的数量


            /// <summary>
            /// 基本记量单位 ,对应K3的 FUnitID
            /// </summary>
            public string FBaseUnitID;      //基本记量单位    

            /// <summary>
            /// 基本记量单位的价格, 对应K3的 FPrice
            /// </summary>
            public double FBasePrice;       //基本记量单位的价格

            /// <summary>
            /// 税率 
            /// </summary>
            public double FTaxRate;     //税率
            
            ///<summary>
            ///税率总金额   FBaseAmount * FTaxRate
            /// </summary>            
            public double FTaxAmount;


            /// <summary>
            /// 折扣率
            /// </summary>
            public double FDisRate;     // 折扣率

            /// <summary>
            /// 折扣金额  对应金蝶中的 FTaxAmount ，  出厂价*税率
            /// </summary>
            public double FDisAmt;     // 折扣金额

            /// <summary>
            /// 折扣价格  
            /// </summary>
            public double FDisPrice;     // 折扣价格

            /// <summary>
            /// 交货日期 
            /// </summary>
            public DateTime FDate;   //交货日期 

            /// <summary>
            /// 建议交货日期 
            /// </summary>
            public DateTime FAdviceConsignDate;   //建议交货日期 

            /// <summary>
            /// 扣税后的金额  FBaseQty * FBasePrice * (1- FDisRate*0.01)
            /// </summary>
            public double FBaseAmount;

            /// <summary>
            /// 出厂价格*单位Rate
            /// </summary>
            public double FAuxTaxPrice;

            /// <summary>
            /// 出厂价格
            /// </summary>
            public double FTaxPrice;

            /// <summary>
            /// 出厂单价 -- 0.72   ？？？？？？  是不是应该是金额来着，需要确认
            /// </summary>
            public double FEntrySelfS0161;

            /// <summary>
            /// 出厂实价 -- 0.72*(1-0.05) =0.684
            /// </summary>
            public double FEntrySelfS0162;   
            
            /// <summary>
            /// 出厂金额 -- 4320 * 0.72   FQty*FEntrySelfS0161
            /// </summary>
            public double FEntrySelfS0163;

            /// <summary>
            /// 
            /// </summary>
            public double FCESS;

            /// <summary>
            /// 物料的颜色
            /// </summary>
            public string FEntrySelfS0168;

            /// <summary>
            /// 记录网站中行的rec_id
            /// </summary>
            public int FEntrySelfS0171;


            /// <summary>
            /// AuxUnit和BaseUnit之间的转换关系
            /// </summary>
            public double dblRate;

            /// <summary>
            /// 传递mary_order_info表中tel、mobile字段传递到k3销售订单上的客户电话（FHeadSelfS0157）字段，传递到k3后的格式为：tel，mobile
            /// </summary>
            public string FHeadSelfS0157;

        }

        private OrderInfo mcurOrder = new OrderInfo();
        
        private bool CheckServerAndDB(DBAccess dbWebCon , DBAccess dbCon, string strKeyValue)
        {
            string strDBName = dbCon.Connection.Database; 
            string strSQL = @"SELECT count(*) FROM mary_order_info A inner join mary_mdc B on A.mdc_id=B.id and B.region_dbName='"+ strDBName +"'";
            strSQL += " where A.order_id='"+ strKeyValue +"'";
            DataRow drCheckDB = dbWebCon.GetDataFirstRow(strSQL);
            if (CvtFunc.ToDouble(drCheckDB[0]) == 0)
            {
                LogManager.Debug(string.Format("不是对应数据库！"));
                return false;
            }
            return true;
        }

        public void Delete(DBAccess dbWebCon, DBAccess dbCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType)
        {
            if (!CheckServerAndDB(dbWebCon, dbCon, strKeyValue))
            {
                return ;
            }
        }

        public void Add(DBAccess dbWebCon, DBAccess dbCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType)
        {
            if (!CheckServerAndDB(dbWebCon, dbCon, strKeyValue))
            {
                return;      
            }
            if (mFromType == Web.OeSalesOrderDAL.FromType.SEOrder)
            {
                if (!AddSales(dbWebCon, dbCon, strKeyValue))
                {
                    throw new MaxLeafException("添加销售单失败！");
                    return;
                }
            }
        }

        public void Update(DBAccess dbWebCon, DBAccess dbCon, string strKeyValue, Web.OeSalesOrderDAL.FromType mFromType)
        {
            if (!CheckServerAndDB(dbWebCon, dbCon, strKeyValue))
            {
                return ;
            }
            if (mFromType == Web.OeSalesOrderDAL.FromType.SEOrder)
            {
                if (!UpdateSales(dbWebCon, dbCon, strKeyValue))
                {
                    throw new Exception("更新销售单失败！");
                    return;
                }
            }            
        }


        private bool AddSales(DBAccess dbWebCon, DBAccess dbCon, string strKeyValue)
        {

            string strSQL = "select * from " + mstrOEHDR_Web + " where order_id='" + strKeyValue + "'";
            DataRow drWebHdr = dbWebCon.GetDataFirstRow(strSQL);
            if (drWebHdr == null) return false;
            strSQL = "select finterid, fbillno from seorder where fheadselfS0167='" + CvtFunc.ToString(drWebHdr["order_sn"]) + "'";
            DataRow drCheck = dbCon.GetDataFirstRow(strSQL); 
            if ( drCheck !=null )
            {
                dbWebCon.ExecuteSql("delete from mLog where KeyValue='" + strKeyValue + "' and LogType='seorder'");
                throw new MaxLeafException("网站销售单" +  CvtFunc.ToString(drWebHdr["order_sn"]) +" 已经产生过，请检查，其对应K3销售单号为：" + CvtFunc.ToString (drCheck["FbillNo"]));
            }
            if (AddSalesHdr(dbWebCon, dbCon, drWebHdr))
            {
                if (AddSalesDetail(dbWebCon, dbCon, drWebHdr))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }

        private string GetBillNo(DBAccess dbCon)
        {
            //geticbillno('0','81' )
            // strSql = "UnitCnv '" + strItemNo + "'," + dFromQty + ",'" + strFromUnit + "','" + strToUnit + "'";
            // dToQty = dBAccess.GetDoubleValue(strSql);
                      
            string strBillNo = "";
            //string strSQL = " GetIcBillNo '0', '81', '" + strBillNo + "'";
            //strBillNo = dbCon.GetValue(strSQL);
            
            strBillNo = dbCon.GetValue("exec GetIcBillNo @IsSave,@FBillType,@BillId output"
                    , new SqlParameter[] {
                        new SqlParameter("@IsSave", "1")
                        ,new SqlParameter("@FBillType","81")
                        ,new SqlParameter("@BillID",SqlDbType.VarChar,50)
                    }
                    , "BillID");

            //System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand();
            //comm.CommandType = CommandType.StoredProcedure;
            //comm.Connection = dbCon.Connection as System.Data.SqlClient.SqlConnection  ;
            //comm.CommandText = strSQL;
            //comm.Transaction = (dbCon.Connection as System.Data.SqlClient.SqlConnection).BeginTransaction (
            //strBillNo = CvtFunc.ToString(  comm.ExecuteScalar()); 
            string strMaxValue = strBillNo.Substring(5,strBillNo.Length -6);
            strBillNo = "SEORD" + BaseFunctions.FormatWithZero(strMaxValue, 6);
            dbCon.ExecuteSql("update t_BillCodeRule set FProjectVal = FProjectVal+1 where FBillTypeID=81 and FClassIndex=2 and FProjectID=3");
            dbCon.ExecuteSql("update ICBillNo set FDesc='SEORD+'+'" + BaseFunctions.FormatWithZero(strMaxValue, 6) + "' where FBillID=81");

            return strBillNo;
        }

        private string GetFinterID(DBAccess dbCon)
        {
            //GetICMaxNum
            // ALTER PROCEDURE [dbo].[GetICMaxNum]
            //@TableName VARCHAR (50),  
            //@FInterID  int output,    
            //@Increment INT = 1 ,   
            //@UserID    int =0 ---增加用户ID
            string strFinterID = "";
            strFinterID = dbCon.GetValue("exec GetICMaxNum @TableName,@FInterID output,@Increment,@UserID"
                  , new SqlParameter[] {
                        new SqlParameter("@TableName", "SEORDER")
                        ,new SqlParameter("@FInterID",SqlDbType.Int)
                        ,new SqlParameter("@Increment","1")
                        ,new SqlParameter("@UserID","0")                        
                    }
                  , "FInterID");

            return strFinterID; 
        }

        private bool AddSalesHdr(DBAccess dbWebCon, DBAccess dbCon, DataRow drWebHdr)
        {
            string strCheckerName="网站审核";
            ServerInfo K3Master = ServerInfo.GetK3MasterServer();
            using (DBAccess dbK3Master = new DBAccess(K3Master))
            {
                string strBillNo = GetBillNo(dbCon);
                string strFinterID = GetFinterID(dbCon);
                string strSQL = "select user_department,user_clerk from mary_users where user_id='" + drWebHdr["user_id"] + "'";
                DataRow drMary_User = dbWebCon.GetDataFirstRow(strSQL);
                if (drWebHdr != null)
                {
                    strSQL = "select top 0 * from seOrder";
                    DataRow drNewK3Hdr = dbCon.GetDataTable(strSQL).NewRow();
                    #region 添加到K3的表头
                    drNewK3Hdr["FBrNo"] = "0"; 
                    drNewK3Hdr["finterid"] =CvtFunc.ToInt ( strFinterID);
                    drNewK3Hdr["fbillno"] = strBillNo;
                    drNewK3Hdr["Fcurrencyid"] = "1";
                    drNewK3Hdr["FcustID"]  =dbWebCon.GetValue ("select FItemID from mary_users where user_id='" + CvtFunc.ToString(drWebHdr["user_id"]) +"'");
                    drNewK3Hdr["Fdate"] = CvtFunc.ToDateTime(CvtFunc.ToLong(drWebHdr["confirm_time"])).ToShortDateString() ;
                    drNewK3Hdr["FsaleStyle"] = (CvtFunc.ToString(drWebHdr["pay_id"]) == "3" ? "100" : "101");
                    drNewK3Hdr["FHeadSelfS0150"] = CvtFunc.ToString(drWebHdr["pay_name"]);
                    drNewK3Hdr["FHeadSelfS0168"] = DateTime.Now.ToString(); 
                    //if (CvtFunc.ToString(drMary_User["user_department"]) != "")
                    //{
                        //这里分发可能有问题，明天要看看
                        //drNewK3Hdr["FdeptID"] = CvtFunc.ToInt(new K3.t_departmentDAL().GetDestMapKeyValue(dbK3Master, dbCon, CvtFunc.ToString(drMary_User["user_department"])));
                    drNewK3Hdr["FdeptID"] = CvtFunc.ToInt(new K3.t_departmentDAL().GetDestMapKeyValue(dbK3Master, dbCon, CvtFunc.ToString(drWebHdr["FDepartID"])));                        
                    //}
                    //if (CvtFunc.ToString(drMary_User["user_clerk"]) != "")
                    //{
                        //这里分发可能有问题，明天要看看 //CvtFunc.ToInt(new K3.t_Base_EmpDAL().GetDestMapKeyValue(dbK3Master, dbCon, CvtFunc.ToString(drMary_User["user_clerk"])));
                    drNewK3Hdr["FEmpID"] = CvtFunc.ToInt(new K3.t_Base_EmpDAL().GetDestMapKeyValue(dbK3Master, dbCon, CvtFunc.ToString(drWebHdr["FEmpID"])));
                        
                        //drNewK3Hdr["Fcheckerid"]=  drNewK3Hdr["FEmpID"];
                        //网站过来的单子由审核人是“网站审核”
                        drNewK3Hdr["Fcheckerid"] =CvtFunc.ToInt ( dbCon.GetValue("select FuserID from t_Base_User where fname='"+ strCheckerName +"'")) ;
                        drNewK3Hdr["fbillerid"] = drNewK3Hdr["Fcheckerid"];
                        drNewK3Hdr["fmangerid"] = drNewK3Hdr["FEmpID"];
                    //}
                    drNewK3Hdr["Ftrantype"] = "81";
                    drNewK3Hdr["finvoiceclosed"] = "0";
                    drNewK3Hdr["fbclosed"] = "0";
                    
                    drNewK3Hdr["fsettleid"] = "0";
                    drNewK3Hdr["fexchangerate"] = "1";
                    drNewK3Hdr["fdiscounttype"] = false ;
                    drNewK3Hdr["fstatus"] = "1";
                    drNewK3Hdr["fcancellation"] = false;
                    drNewK3Hdr["Fcheckdate"] = drNewK3Hdr["Fdate"];
                    drNewK3Hdr["Fsettledate"] = drNewK3Hdr["Fdate"];
                    drNewK3Hdr["fseltrantype"] = "0";
                    drNewK3Hdr["fchildren"] = "0";
                    //这两个字段要特殊取
                    drNewK3Hdr["fbrid"] = dbCon.GetValue("select top 1 fbrid from seorder") ;
                    drNewK3Hdr["fareaps"] = dbCon.GetValue("select top 1 fareaps from seorder");
                    //
                    drNewK3Hdr["fsysstatus"] = "2";
                    //drNewK3Hdr["fheadselfS0144"] = CvtFunc.ToString(drWebHdr["address"]);
                    drNewK3Hdr["fheadselfS0160"] = CvtFunc.ToString(drWebHdr["shipping_name"]);
                    drNewK3Hdr["fheadselfS0161"] = CvtFunc.ToString(drWebHdr["address"]);
                    drNewK3Hdr["fheadselfS0162"] = CvtFunc.ToString(drWebHdr["inv_type"]);
                    drNewK3Hdr["fheadselfS0163"] = CvtFunc.ToString(drWebHdr["inv_payee"]);
                    drNewK3Hdr["fheadselfS0164"] = CvtFunc.ToString(drWebHdr["inv_content"]);
                    drNewK3Hdr["fheadselfS0165"] = CvtFunc.ToString(drWebHdr["consignee"]);
                    drNewK3Hdr["fheadselfS0166"] = CvtFunc.ToString(drWebHdr["postscript"]);
                    drNewK3Hdr["fheadselfS0167"] = CvtFunc.ToString(drWebHdr["order_sn"]);
                    if (K3Master.AcctType == "bj" ||  K3Master.AcctType == "wh")
                    {
                        drNewK3Hdr["FHeadSelfS0157"] =( CvtFunc.ToString(drWebHdr["Tel"])=="" ? "" :  CvtFunc.ToString(drWebHdr["Tel"])) + " " + ( CvtFunc.ToString(drWebHdr["Mobile"])=="" ? "": ", " +  CvtFunc.ToString(drWebHdr["Mobile"]));
                    }
                    #endregion
                    KeyValuePair<string, IDataParameter[]> kvp = dbCon.CreateParamSql(mstrFieldNamesHDR_K3,mstrOEHDR_K3, drNewK3Hdr, LogStatus.Add, "finterid");
                    dbCon.ExecuteSql(kvp.Key, kvp.Value);

                    #region Set mCurOrderInfo
                    mcurOrder.CustID = CvtFunc.ToString(drNewK3Hdr["FcustID"]);
                    mcurOrder.FInterID = strFinterID;
                    mcurOrder.BillNo_K3 = strBillNo;
                    mcurOrder.BillNo_Web = CvtFunc.ToString(drWebHdr["order_sn"]);
                    mcurOrder.CustTypeID = dbCon.GetValue("select ftypeid from t_organization where fitemid='" + mcurOrder.CustID + "'");
                    mcurOrder.FDate = CvtFunc.ToDateTime(drNewK3Hdr["FDate"]);
                    #endregion
                }
                else
                {
                    return false;
                }
                return true;
            }
        }

        private double GetDefPrice(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail)
        {
            double dblPrice = 0;
            string strFunitID="";
            bool dvRowPrice = GetDefPriceRow(dbWebCon, dbCon, newOrderDetail, ref  strFunitID, ref  dblPrice);
            //if (dvRowPrice != null)
            //{
            //    dblPrice = CvtFunc.ToDouble(dvRowPrice["FPrice"]);
            //}           
            return dblPrice;
        }

        private bool GetDefPriceRow_OLD(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail, ref string strFUnitID, ref double dblPrice)
        {
            //select * from icprcplyentry where fitemid=7364 and frelatedid =40001  --fitemid 指的是物料的ID  frelatedid指的是客户类型
            string strSQL = "";
            strSQL = "select DTL.* from icprcplyentry DTL inner join icprcply HDR on DTL.FInterID=HDR.FInterID where Hdr.Fnumber<>'99901' and DTL.fitemid='" + newOrderDetail.FItemID + "' and DTL.frelatedid ='" + mcurOrder.CustTypeID + "' and DTL.FChecked=1 ";
            DataTable dtPrice = dbCon.GetDataTable(strSQL);
            DataView dvPrice = dtPrice.DefaultView;
            if (dtPrice.Rows.Count > 0)
            {
                foreach (DataRow drPrice in dtPrice.Rows)
                {
                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' ";
                    if (dvPrice.Count > 0)
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                        if (dvPrice.Count > 0)
                        {
                            dvPrice.Sort = "FBegDate Desc";
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + newOrderDetail.FAuxQty + "' and FEndQty>='" + newOrderDetail.FAuxQty + "' ";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = " FBegDate Desc";
                                strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                return true;
                            }
                            else
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                {
                                    strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "'";
                            strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                            dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                            return true;
                        }
                    }
                    else  //如果没有找到销售单位的，则需要做到基本单位的单价
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' ";
                        if (dvPrice.Count > 0)
                        {
                            double dblBaseQty = newOrderDetail.FAuxQty * newOrderDetail.dblRate;
                            //-----------------------------------------------------------------
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + dblBaseQty + "' and FEndQty>='" + dblBaseQty + "' ";
                                if (dvPrice.Count > 0)
                                {
                                    dvPrice.Sort = " FBegDate Desc";
                                    strFUnitID = newOrderDetail.FAuxUnitID;
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                    return true;
                                }
                                else
                                {
                                    dvPrice.Sort = "FBegDate Desc";
                                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                    if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                    {
                                        strFUnitID = newOrderDetail.FAuxUnitID;
                                        dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                        return true;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }
                            else
                            {
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "'";
                                strFUnitID = newOrderDetail.FAuxUnitID;
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                return true;
                            }
                            //---------------------------------------------------------------                           
                        }
                    }
                }
            }
            return false;
        }

        private bool GetDefPriceRow_BJ(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail, ref string strFUnitID, ref double dblPrice)
        {
            //select * from icprcplyentry where fitemid=7364 and frelatedid =40001  --fitemid 指的是物料的ID  frelatedid指的是客户类型
            string strSQL = "";
            strSQL = "select DTL.* from icprcplyentry DTL inner join icprcply HDR on DTL.FInterID=HDR.FInterID where 1=1 " +
                     " and  DTL.FUnitID='" + newOrderDetail.FAuxUnitID + "' and DTL.fitemid='" + newOrderDetail.FItemID + "' and DTL.frelatedid ='" + mcurOrder.CustTypeID + "' and DTL.FChecked=1 ";
            DataTable dtPrice = dbCon.GetDataTable(strSQL);
            DataView dvPrice = dtPrice.DefaultView;
            if (dtPrice.Rows.Count > 0)
            {
                foreach (DataRow drPrice in dtPrice.Rows)
                {
                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' ";
                    if (dvPrice.Count > 0)
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                        if (dvPrice.Count > 0)
                        {
                            dvPrice.Sort = "FBegDate Desc";
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + newOrderDetail.FAuxQty + "' and FEndQty>='" + newOrderDetail.FAuxQty + "' ";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = " FBegDate Desc";
                                strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                return true;
                            }
                            else
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                {
                                    strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "'";
                            strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                            dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                            return true;
                        }
                    }
                    else  //如果没有找到销售单位的，则需要做到基本单位的单价
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' ";
                        if (dvPrice.Count > 0)
                        {
                            double dblBaseQty = newOrderDetail.FAuxQty * newOrderDetail.dblRate;
                            //-----------------------------------------------------------------
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + dblBaseQty + "' and FEndQty>='" + dblBaseQty + "' ";
                                if (dvPrice.Count > 0)
                                {
                                    dvPrice.Sort = " FBegDate Desc";
                                    strFUnitID = newOrderDetail.FAuxUnitID;
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                    return true;
                                }
                                else
                                {
                                    dvPrice.Sort = "FBegDate Desc";
                                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                    if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                    {
                                        strFUnitID = newOrderDetail.FAuxUnitID;
                                        dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                        return true;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }
                            else
                            {
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "'";
                                strFUnitID = newOrderDetail.FAuxUnitID;
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                return true;
                            }
                            //---------------------------------------------------------------                           
                        }
                    }
                }
            }
            return false;
        }


        private bool GetDefPriceRow(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail,ref string strFUnitID, ref double dblPrice)
        {
            //select * from icprcplyentry where fitemid=7364 and frelatedid =40001  --fitemid 指的是物料的ID  frelatedid指的是客户类型
            string strSQL = "";
            strSQL = "select DTL.* from icprcplyentry DTL inner join icprcply HDR on DTL.FInterID=HDR.FInterID where Hdr.Fnumber='99901' " +
                     " and  DTL.FUnitID='" + newOrderDetail.FAuxUnitID + "' and DTL.fitemid='" + newOrderDetail.FItemID + "' and DTL.frelatedid ='" + mcurOrder.CustTypeID + "' and DTL.FChecked=1 ";
            DataTable dtPrice = dbCon.GetDataTable(strSQL);
            DataView dvPrice = dtPrice.DefaultView;
            if ( dtPrice.Rows.Count>0)
            {
                foreach (DataRow drPrice in dtPrice.Rows)
                {
                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' ";
                    if (dvPrice.Count > 0)
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                        if (dvPrice.Count > 0)
                        {
                            dvPrice.Sort = "FBegDate Desc";                            
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + newOrderDetail.FAuxQty + "' and FEndQty>='" + newOrderDetail.FAuxQty + "' ";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = " FBegDate Desc";
                                strFUnitID =CvtFunc.ToString ( dvPrice[0]["FUnitID"]);
                                dblPrice  = CvtFunc.ToDouble ( dvPrice[0]["FPrice"]); 
                                return true ;
                            }
                            else
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                {
                                    strFUnitID =CvtFunc.ToString ( dvPrice[0]["FUnitID"]);
                                    dblPrice  = CvtFunc.ToDouble ( dvPrice[0]["FPrice"]); 
                                    return true ;
                                }
                                else
                                {
                                    return false ;
                                }
                            }
                        }
                        else
                        {
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "'";
                            strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                            dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                            return true;
                        }
                    }
                    else  //如果没有找到销售单位的，则需要做到基本单位的单价
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' ";
                        if (dvPrice.Count > 0)
                        {
                            double dblBaseQty = newOrderDetail.FAuxQty * newOrderDetail.dblRate;
                            //-----------------------------------------------------------------
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + dblBaseQty + "' and FEndQty>='" + dblBaseQty + "' ";
                                if (dvPrice.Count > 0)
                                {
                                    dvPrice.Sort = " FBegDate Desc";
                                    strFUnitID = newOrderDetail.FAuxUnitID ;
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"])* newOrderDetail.dblRate ;
                                    return true;
                                }
                                else
                                {
                                    dvPrice.Sort = "FBegDate Desc";
                                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                    if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                    {
                                        strFUnitID = newOrderDetail.FAuxUnitID ;
                                        dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                        return true;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }
                            else
                            {
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "'";
                                strFUnitID = newOrderDetail.FAuxUnitID ;
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                return true;
                            }
                            //---------------------------------------------------------------                           
                        }
                    }
                }               
            }
            return false  ;
        }

        private bool GetDefPriceRow_ByCustID(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail, ref string strFUnitID, ref double dblPrice)
        {
            //select * from icprcplyentry where fitemid=7364 and frelatedid =40001  --fitemid 指的是物料的ID  frelatedid指的是客户类型
            string strSQL = "";
            strSQL = "select DTL.* from icprcplyentry DTL inner join icprcply HDR on DTL.FInterID=HDR.FInterID where Hdr.Fnumber<>'99901' and  Hdr.Fnumber='99902'" +
                     " and  DTL.FUnitID='" + newOrderDetail.FAuxUnitID + "' and DTL.fitemid='" + newOrderDetail.FItemID + "' and DTL.frelatedid ='" + mcurOrder.CustID + "' and DTL.FChecked=1 ";
            DataTable dtPrice = dbCon.GetDataTable(strSQL);
            DataView dvPrice = dtPrice.DefaultView;
            if (dtPrice.Rows.Count > 0)
            {
                foreach (DataRow drPrice in dtPrice.Rows)
                {
                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' ";
                    if (dvPrice.Count > 0)
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                        if (dvPrice.Count > 0)
                        {
                            dvPrice.Sort = "FBegDate Desc";
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + newOrderDetail.FAuxQty + "' and FEndQty>='" + newOrderDetail.FAuxQty + "' ";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = " FBegDate Desc";
                                strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                return true;
                            }
                            else
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                {
                                    strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FAuxUnitID + "'";
                            strFUnitID = CvtFunc.ToString(dvPrice[0]["FUnitID"]);
                            dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]);
                            return true;
                        }
                    }
                    else  //如果没有找到销售单位的，则需要做到基本单位的单价
                    {
                        dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' ";
                        if (dvPrice.Count > 0)
                        {
                            double dblBaseQty = newOrderDetail.FAuxQty * newOrderDetail.dblRate;
                            //-----------------------------------------------------------------
                            dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                            if (dvPrice.Count > 0)
                            {
                                dvPrice.Sort = "FBegDate Desc";
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "' and FBegQty<='" + dblBaseQty + "' and FEndQty>='" + dblBaseQty + "' ";
                                if (dvPrice.Count > 0)
                                {
                                    dvPrice.Sort = " FBegDate Desc";
                                    strFUnitID = newOrderDetail.FAuxUnitID;
                                    dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                    return true;
                                }
                                else
                                {
                                    dvPrice.Sort = "FBegDate Desc";
                                    dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "' and FBegDate<='" + DateTime.Now.Date.ToShortDateString() + "' and FEndDate>='" + DateTime.Now.Date.ToShortDateString() + "'";
                                    if (CvtFunc.ToDouble(dvPrice[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvPrice[0]["FEndQty"]) == 0)
                                    {
                                        strFUnitID = newOrderDetail.FAuxUnitID;
                                        dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                        return true;
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                            }
                            else
                            {
                                dvPrice.RowFilter = " FUnitID='" + newOrderDetail.FBaseUnitID + "'";
                                strFUnitID = newOrderDetail.FAuxUnitID;
                                dblPrice = CvtFunc.ToDouble(dvPrice[0]["FPrice"]) * newOrderDetail.dblRate;
                                return true;
                            }
                            //---------------------------------------------------------------                           
                        }
                    }
                }
            }
            return false;
        }

        private double GetDefDiscount(DBAccess dbWebCon, DBAccess dbCon, OrderDetail newOrderDetail)
        {
            //select * from icdisplyentry where frelatedid =40001 and FItemID=20013  -- FItemID 指的是物料类型 , frelatedid是指客户的类型
            //select * from icdisply
            //优先高的先取，找不到就向下一个级别找 
            //FSysTypeID这个如果=1 表示Freletedid 是客户内码，=501表示Freletedid 取客户类别
            //FItemtypeID=4表示itemid表示物料Fitemid，=504表示物料类别
            double dblFvalue =0;
            string strSQL = "";
            strSQL = "select * from icdisply order by Fpri";
            DataTable dtICDIS = dbCon.GetDataTable(strSQL);
            foreach (DataRow drDic in dtICDIS.Rows)
            {
                string strItem="";
                string strCust="";
                bool blnUseQty = false;
                strSQL = "select * from icdisplyentry where frelatedid ='{0}' and  FItemID='{1}'";
                strSQL += " and FBegDate<=getdate() and FEndDate>=getdate()  and FinterID='{3}' and FChecked=1";
                if (CvtFunc.ToString(drDic["FSysTypeID"]) == "1") //是客户内码
                {
                    strCust = mcurOrder.CustID;
                }
                else if (CvtFunc.ToString(drDic["FSysTypeID"]) == "501") //取客户类别
                {
                    strCust = mcurOrder.CustTypeID;
                }

                if (CvtFunc.ToString(drDic["FItemtypeID"]) == "4") //物料Fitemid
                {
                    strItem = newOrderDetail.FItemID;
                    blnUseQty = true;
                }
                else if (CvtFunc.ToString(drDic["FItemtypeID"]) == "504") //物料类别
                {
                    strItem = newOrderDetail.FItemTypeID;
                }                
                if (blnUseQty) strSQL += " and FUnitID='{2}' ";
                string strSQLUnit = string.Format(strSQL, strCust, strItem, newOrderDetail.FAuxUnitID, CvtFunc.ToString (drDic["FinterID"]) );
                DataTable dtDisc = dbCon.GetDataTable(strSQLUnit);
                double dblQty = newOrderDetail.FAuxQty; // 如果没有这个单位的，则用BaseQty                
                if (dtDisc.Rows.Count == 0)
                {
                    strSQLUnit = string.Format(strSQL, strCust, strItem, newOrderDetail.FBaseUnitID, CvtFunc.ToString (drDic["FinterID"]));
                    dtDisc = dbCon.GetDataTable(strSQLUnit);
                    dblQty = newOrderDetail.FAuxQty * newOrderDetail.dblRate;
                }
                DataView dvDisc = null;
                if (dtDisc.Rows.Count > 0)
                { dvDisc = dtDisc.DefaultView; }
                foreach (DataRow drRow in dtDisc.Rows)
                {
                    if (blnUseQty)
                    {
                        dvDisc.RowFilter = "FBegQty<='" + dblQty + "' and FEndQty>='" + dblQty + "'";
                    }
                    else
                    {
                        dvDisc.RowFilter = "FBegAmt<='" + newOrderDetail.FAuxQty * newOrderDetail.FAuxTaxPrice + "' and FEndAmt>='" + newOrderDetail.FAuxQty * newOrderDetail.FAuxTaxPrice + "'";
                    }
                    if (dvDisc.Count > 0)
                    {
                        dblFvalue = CvtFunc.ToDouble(dvDisc[0]["Fvalue"]);
                        return dblFvalue;
                    }
                    else
                    {
                        dvDisc.RowFilter = "";
                        if (blnUseQty)  // 数量的范围
                        {
                            if (CvtFunc.ToDouble(dvDisc[0]["FBegQty"]) == 0 && CvtFunc.ToDouble(dvDisc[0]["FEndQty"]) == 0)
                            {
                                dblFvalue = CvtFunc.ToDouble(dvDisc[0]["Fvalue"]);
                                return dblFvalue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else  // 金额的范围
                        {
                            if (CvtFunc.ToDouble(dvDisc[0]["FBegAmt"]) == 0 && CvtFunc.ToDouble(dvDisc[0]["FEndAmt"]) == 0)
                            {
                                dblFvalue = CvtFunc.ToDouble(dvDisc[0]["Fvalue"]);
                                return dblFvalue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }
                if (dblFvalue > 0) break;
            }
            return dblFvalue;
        }

        private bool AddSalesDetail(DBAccess dbWebCon, DBAccess dbCon, DataRow drWebHdr)
        {
            ServerInfo server = ServerInfo.GetK3MasterServer();
            
            using (DBAccess dbK3Master = new DBAccess(server))
            {

                int intSeqNo = 1;
                string strKeyFieldName = "FinterID";
                DataRow drItem = null;
                string strSQL = "select * from " + mstrOEDTL_Web  + " where order_id='" + drWebHdr["order_id"] + "' ";
                DataTable dtWebDetail = dbWebCon.GetDataTable(strSQL);
                foreach (DataRow drWebDtl in dtWebDetail.Rows)
                {
                    OrderDetail newOrderDetail = new OrderDetail();
                    strSQL = "select top 0 * from " + mstrOEDTL_K3 + "";
                    DataRow drNewDtl_K3 = dbCon.GetDataTable(strSQL).NewRow();
                    #region 添加K3 的Detail表

                    newOrderDetail.FEntryID = intSeqNo.ToString();
                    strSQL = " select FItemID from mary_goods where goods_id= '" + CvtFunc.ToString(drWebDtl["goods_id"]) + "' ";
                    string strWebFitemID = dbWebCon.GetValue(strSQL);
                    newOrderDetail.FItemID = new ImInvMasterDAL().GetDestMapKeyValue(dbK3Master, dbCon, strWebFitemID);
                    newOrderDetail.FInterID = mcurOrder.FInterID;
                    newOrderDetail.FAuxQty = CvtFunc.ToDouble(drWebDtl["goods_number"]);
                    strSQL = " select A.*,B.Fmeasureunitid from t_icItem A inner join t_measureunit B on A.FunitGroupID= B.FunitGroupID and ";
                    strSQL += " A.FItemID='" + newOrderDetail.FItemID + "' ";
                    strSQL += " and B.FName='"+ CvtFunc.ToString ( drWebDtl["goods_unit"])  +"'";
                    drItem = dbCon.GetDataFirstRow(strSQL);
                    if (drItem != null)
                    {
                        newOrderDetail.FBaseUnitID = CvtFunc.ToString(drItem["FUnitID"]);
                        newOrderDetail.FAuxUnitID = CvtFunc.ToString(drItem["Fmeasureunitid"]);
                        newOrderDetail.FTaxRate = CvtFunc.ToDouble(drItem["FTaxRate"]);   // 此物料的税率 
                        newOrderDetail.FCESS = newOrderDetail.FTaxRate;
                        newOrderDetail.FItemTypeID = CvtFunc.ToString(drItem["FTypeID"]); ;
                    }
                    else
                    {
                        throw new MaxLeafException(CvtFunc.ToString(drWebHdr["order_sn"]) + CvtFunc.ToString(drWebDtl["goods_name"]) + "  没有找到与之对应的 sales unit." + CvtFunc.ToString(drWebDtl["goods_unit"])); 
                        return false;  //没有找到与之对应的 sales unit.
                    }
                    if (CvtFunc.ToBoolean(drWebDtl["is_gift"])) // 如果这个一行是礼物，则单价要清0，金额也要是0
                    {
                        newOrderDetail.FBasePrice = 0.01;
                        newOrderDetail.FBaseAmount = 0.01;
                    }
                    else
                    {
                        string strFunitID = "";
                        double dblFPrice = 0;
                       
                        
                        double dblRate = 1;
                        string strFunit = "";
                        double dblPrice = 0;
                        double dblPrice_ByCust = 0;
                        if (newOrderDetail.FBaseUnitID != newOrderDetail.FAuxUnitID)
                        {
                            strSQL = "select * from t_measureunit where FunitGroupID='{0}'and Fmeasureunitid='{1}'";
                            strSQL = string.Format(strSQL, CvtFunc.ToString(drItem["FunitGroupID"]), newOrderDetail.FAuxUnitID);
                            DataRow drRate = dbCon.GetDataFirstRow(strSQL);
                            if (drRate != null)
                            {
                                dblRate = CvtFunc.ToDouble(drRate["Fcoefficient"]);
                            }
                        }
                        newOrderDetail.dblRate = dblRate;

                        bool blnIsBegin = true ;
                        if (server.AcctType == "bj" || server.AcctType == "wh")
                        {
                            blnIsBegin = false;
                        }

                        //按customer ID找
                        bool dvRowPrice_ByCustID = GetDefPriceRow_ByCustID(dbWebCon, dbCon, newOrderDetail, ref strFunitID, ref dblFPrice);
                        if (dvRowPrice_ByCustID)
                        {
                            strFunit = strFunitID;
                            dblPrice = dblFPrice;
                        }
                        else
                        {
                            //按customer Type找
                            bool dvRowPrice = GetDefPriceRow(dbWebCon, dbCon, newOrderDetail, ref strFunitID, ref dblFPrice);
                            if (dvRowPrice)
                            {
                                strFunit = strFunitID;                                
                                dblPrice = dblFPrice;                                
                            }
                            else
                            {
                                dblPrice = CvtFunc.ToDouble(drWebDtl["goods_price"]);
                            }
                        }

                        #region false 
                        //if (false)
                        //{
                        //    if (blnIsBegin)
                        //    {
                        //        #region 如是要北京的就用此价格政策
                        //        bool dvRowPrice = GetDefPriceRow_BJ(dbWebCon, dbCon, newOrderDetail, ref strFunitID, ref dblFPrice);
                        //        if (dvRowPrice)
                        //        {
                        //            strFunit = strFunitID;
                        //            if (dblFPrice < CvtFunc.ToDouble(drWebDtl["goods_price"]))
                        //            {
                        //                dblPrice = dblFPrice;
                        //            }
                        //            else
                        //            {
                        //                dblPrice = CvtFunc.ToDouble(drWebDtl["goods_price"]);
                        //            }
                        //        }
                        //        else
                        //        {
                        //            dblPrice = CvtFunc.ToDouble(drWebDtl["goods_price"]);
                        //        }
                        //        #endregion
                        //    }
                        //    else
                        //    {
                        //        #region 全国价格政策
                        //        bool dvRowPrice_ByCustID = GetDefPriceRow_ByCustID(dbWebCon, dbCon, newOrderDetail, ref strFunitID, ref dblFPrice);
                        //        if (dvRowPrice_ByCustID)
                        //        {
                        //            strFunit = strFunitID;
                        //            if (dblFPrice < CvtFunc.ToDouble(drWebDtl["goods_price"]))
                        //            {
                        //                dblPrice_ByCust = dblFPrice;
                        //            }
                        //            else
                        //            {
                        //                dblPrice_ByCust = CvtFunc.ToDouble(drWebDtl["goods_price"]);
                        //            }
                        //        }
                        //        else
                        //        {
                        //            dblPrice_ByCust = CvtFunc.ToDouble(drWebDtl["goods_price"]);
                        //        }

                        //        //if (dblPrice_ByCust < dblPrice) dblPrice = dblPrice_ByCust;  // 取最小单价
                        //        dblPrice = dblPrice_ByCust;
                        //        #endregion
                        //    }
                        //}
                        #endregion
                        //newOrderDetail.FBasePrice = dblPrice / (1.00 + newOrderDetail.FTaxRate * 0.01) / dblRate;

                        if (newOrderDetail.FBaseUnitID == strFunit) // 取的是基本单位
                        {
                            newOrderDetail.FBasePrice = dblPrice / (1.00 + newOrderDetail.FTaxRate * 0.01);
                            newOrderDetail.FAuxPrice = dblRate * newOrderDetail.FBasePrice;
                            newOrderDetail.FAuxTaxPrice = dblPrice * dblRate;
                        }
                        else  //如果取的不是基本单位
                        {
                            newOrderDetail.FBasePrice = dblPrice / (1.00 + newOrderDetail.FTaxRate * 0.01) / dblRate;
                            newOrderDetail.FAuxPrice = dblRate * newOrderDetail.FBasePrice;
                            newOrderDetail.FAuxTaxPrice = dblPrice;
                        }

                        newOrderDetail.FDisRate = GetDefDiscount(dbWebCon, dbCon, newOrderDetail);
                        newOrderDetail.FBaseQty = newOrderDetail.FAuxQty * dblRate;
                        newOrderDetail.FBaseAmount = newOrderDetail.FBaseQty * newOrderDetail.FBasePrice * (1 - newOrderDetail.FDisRate * 0.01);

                        newOrderDetail.FTaxAmount = newOrderDetail.FBaseAmount * newOrderDetail.FTaxRate * 0.01;
                        newOrderDetail.FDisAmt = newOrderDetail.FBaseQty * dblPrice * newOrderDetail.FDisRate * 0.01;

                        if (newOrderDetail.FBaseUnitID == strFunit) // 取的是基本单位
                        {                            
                            newOrderDetail.FTaxPrice = dblPrice ;
                            newOrderDetail.FEntrySelfS0163 = newOrderDetail.FBaseQty * dblPrice / dblRate; //newOrderDetail.FEntrySelfS0161;
                            newOrderDetail.FDisPrice = dblPrice * (1 - newOrderDetail.FDisRate * 0.01) * dblRate;
                        }
                        else
                        {                            
                            newOrderDetail.FTaxPrice = dblPrice/dblRate;
                            newOrderDetail.FEntrySelfS0163 = newOrderDetail.FAuxQty * dblPrice ; //newOrderDetail.FEntrySelfS0161;
                            newOrderDetail.FDisPrice = dblPrice * (1 - newOrderDetail.FDisRate * 0.01);
                        }
                         
                        

                        newOrderDetail.FEntrySelfS0161 = dblPrice;
                        newOrderDetail.FEntrySelfS0162 = dblPrice * (1 - newOrderDetail.FDisRate * 0.01);
                        
                        
                        
                        newOrderDetail.FEntrySelfS0168 = CvtFunc.ToString(drWebDtl["goods_color"]);
                    }

                    newOrderDetail.FEntrySelfS0171 = CvtFunc.ToInt(drWebDtl["rec_id"]);
                    newOrderDetail.FAdviceConsignDate = mcurOrder.FDate;
                    newOrderDetail.FDate = mcurOrder.FDate;
                    #region 把newOrderDetail设置给DATAROW
                    if (!SetOrderDetailToDataRow(newOrderDetail, ref drNewDtl_K3))
                    {
                        throw new MaxLeafException(CvtFunc.ToString(drWebDtl["order_sn"]) + "赋值到DataRow中出错.添加销售单失败。");
                        return false;
                    }
                    #endregion
                    //mcurOrder.Detail.Add(newOrderDetail);  
                    KeyValuePair<string, IDataParameter[]> kvp = dbCon.CreateParamSql(mstrFieldNamesDTL_K3, mstrOEDTL_K3, drNewDtl_K3, LogStatus.Add, "FDetailID");
                    dbCon.ExecuteSql(kvp.Key, kvp.Value);

                    #endregion
                    intSeqNo++;
                }
                #region 把运输费用作为一行加入到Detail中  shipping_fee
                double dblShipFee = CvtFunc.ToDouble(drWebHdr["shipping_fee"]);                                
                if (dblShipFee != 0)
                {
                    OrderDetail newOrderDetailFee = new OrderDetail();
                    strSQL = "select top 0 * from " + mstrOEDTL_K3 + "";
                    DataRow drNewDtlFee = dbCon.GetDataTable(strSQL).NewRow();
                    {
                        newOrderDetailFee.FItemID = dbCon.GetValue("select FItemID from t_icitem where f_137='1'");
                        strSQL = " select A.*,B.Fmeasureunitid from t_icItem A inner join t_measureunit B on A.FunitGroupID= B.FunitGroupID and ";
                        strSQL += " A.FItemID='" + newOrderDetailFee.FItemID + "' and A.F_137='1' ";
                        drItem = dbCon.GetDataFirstRow(strSQL);
                        if (drItem != null)
                        {
                            newOrderDetailFee.FBaseUnitID = CvtFunc.ToString(drItem["FUnitID"]);
                            newOrderDetailFee.FAuxUnitID = CvtFunc.ToString(drItem["Fmeasureunitid"]);
                            newOrderDetailFee.FTaxRate = CvtFunc.ToDouble(drItem["FTaxRate"]);   // 此物料的税率 
                            newOrderDetailFee.FCESS = newOrderDetailFee.FTaxRate;
                        }
                        else
                        {
                            throw new MaxLeafException(CvtFunc.ToString(drWebHdr["order_sn"]) + "添加运费失败。添加销售单失败。");
                            return false;
                        }
                        newOrderDetailFee.FInterID = mcurOrder.FInterID;
                        newOrderDetailFee.FDisRate = GetDefDiscount(dbWebCon, dbCon, newOrderDetailFee);
                        newOrderDetailFee.FEntryID = intSeqNo.ToString();
                        newOrderDetailFee.FBaseQty = 1;
                        double dblPrice = dblShipFee;
                        double dblRate = 1;
                        newOrderDetailFee.FBasePrice = dblPrice / (1.00 + newOrderDetailFee.FTaxRate * 0.01);
                        newOrderDetailFee.FAuxPrice = dblRate * newOrderDetailFee.FBasePrice;
                        newOrderDetailFee.FAuxQty = 1;
                        newOrderDetailFee.FBaseAmount = newOrderDetailFee.FBaseQty * newOrderDetailFee.FBasePrice * (1 - newOrderDetailFee.FDisRate * 0.01);

                        newOrderDetailFee.FTaxAmount = newOrderDetailFee.FBaseAmount * newOrderDetailFee.FTaxRate * 0.01;
                        newOrderDetailFee.FDisAmt = dblPrice * newOrderDetailFee.FDisRate * 0.01;

                        newOrderDetailFee.FAuxTaxPrice = dblPrice * dblRate;
                        newOrderDetailFee.FTaxPrice = dblPrice;
                        newOrderDetailFee.FDisPrice = dblPrice * (1 - newOrderDetailFee.FDisRate * 0.01);
                        newOrderDetailFee.FEntrySelfS0161 = dblPrice;
                        newOrderDetailFee.FEntrySelfS0162 = dblPrice * (1 - newOrderDetailFee.FDisRate * 0.01);
                        newOrderDetailFee.FEntrySelfS0163 = newOrderDetailFee.FBaseQty * newOrderDetailFee.FEntrySelfS0161;
                        newOrderDetailFee.FAdviceConsignDate = mcurOrder.FDate;
                        newOrderDetailFee.FDate = mcurOrder.FDate;
                        newOrderDetailFee.dblRate = 1;
                        newOrderDetailFee.FEntrySelfS0171 = 999;  //这里给个999只是为了让这个行对应是最后一行。
                        //mcurOrder.Detail.Add(newOrderDetailFee);
                        if (!SetOrderDetailToDataRow(newOrderDetailFee, ref drNewDtlFee))
                        {
                            throw new MaxLeafException(CvtFunc.ToString(drWebHdr["order_sn"]) +" 赋值到DataRow中出错.添加销售单失败。");
                            return false;
                        }
                        KeyValuePair<string, IDataParameter[]> kvp = dbCon.CreateParamSql(mstrFieldNamesDTL_K3, mstrOEDTL_K3, drNewDtlFee, LogStatus.Add, "FDetailID");
                        dbCon.ExecuteSql(kvp.Key, kvp.Value);
                    }
                }
                #endregion
                return true;
            }
        }

        private bool SetOrderDetailToDataRow(OrderDetail newOrderDetail,ref DataRow drNewDtl_K3)
        {
            drNewDtl_K3["FBrNO"] = "0";
            drNewDtl_K3["FInterID"] = CvtFunc.ToInt ( newOrderDetail.FInterID ) ;
            drNewDtl_K3["FEntryID"] = CvtFunc.ToInt ( newOrderDetail.FEntryID ) ;
            drNewDtl_K3["FItemID"] =  CvtFunc.ToInt ( newOrderDetail.FItemID );
            drNewDtl_K3["FQty"] = newOrderDetail.FBaseQty;
            drNewDtl_K3["FCommitQty"] = "0";
            drNewDtl_K3["FPrice"] = newOrderDetail.FBasePrice;
            drNewDtl_K3["FAmount"] = newOrderDetail.FBaseAmount;
            drNewDtl_K3["FTaxRate"] = newOrderDetail.FDisRate;
            drNewDtl_K3["FTaxAmount"] = newOrderDetail.FAuxQty*newOrderDetail.FAuxTaxPrice* newOrderDetail.FDisRate*0.01;  //折扣金额
            drNewDtl_K3["FTax"] = "0";
            drNewDtl_K3["FDiscount"] = "0";
            drNewDtl_K3["FNote"] = "";
            drNewDtl_K3["FDate"] =newOrderDetail.FDate;
            drNewDtl_K3["FAdviceConsignDate"] = newOrderDetail.FAdviceConsignDate;
            drNewDtl_K3["FDiscountAmount"] = newOrderDetail.FTaxAmount ;
            drNewDtl_K3["FInvoiceQty"] = "0";
            drNewDtl_K3["FBCommitQty"] = "0";
            drNewDtl_K3["FTranLeadTime"] = "0";
            drNewDtl_K3["FATPDeduct"] = "0";
            drNewDtl_K3["FCostObjectID"] = "0";
            drNewDtl_K3["FUnitID"] = newOrderDetail.FAuxUnitID;
            drNewDtl_K3["FAuxPrice"] = newOrderDetail.FAuxPrice;
            drNewDtl_K3["FAuxQty"] = newOrderDetail.FAuxQty;
            drNewDtl_K3["FCESS"] = newOrderDetail.FCESS;
            drNewDtl_K3["FAllAmount"] = newOrderDetail.FDisPrice * newOrderDetail.FAuxQty;
            drNewDtl_K3["FAllStdAmount"] = drNewDtl_K3["FAllAmount"];
            drNewDtl_K3["FTaxAmt"] = newOrderDetail.FTaxAmount;
            drNewDtl_K3["FAuxPriceDiscount"] = newOrderDetail.FDisPrice;//newOrderDetail.FAuxTaxPrice;
            drNewDtl_K3["FPriceDiscount"] = newOrderDetail.FDisPrice/newOrderDetail.dblRate;
            
            drNewDtl_K3["FAuxTaxPrice"] = newOrderDetail.FAuxTaxPrice;
            drNewDtl_K3["FTaxPrice"] = newOrderDetail.FTaxPrice;
            //drNewDtl_K3["FDetailID,
            //rNewDtl_K3["FMrpAutoClosed,
            //drNewDtl_K3["FSecStockQty,
            //drNewDtl_K3["FSecInvoiceQty,
            //drNewDtl_K3["FSecCommitInstall,

            drNewDtl_K3["FStockQty"] = 0; //newOrderDetail.FBaseQty;
            drNewDtl_K3["FAuxStockQty"] = 0; // newOrderDetail.FAuxQty;
            //drNewDtl_K3["FcommitQty"] = newOrderDetail.FBaseQty; 
            drNewDtl_K3["FPlanMode"] = "14036";
            drNewDtl_K3["FEntrySelfS0161"] = newOrderDetail.FEntrySelfS0161 / newOrderDetail.dblRate ;
            drNewDtl_K3["FEntrySelfS0162"] = newOrderDetail.FEntrySelfS0162 / newOrderDetail.dblRate;
            drNewDtl_K3["FEntrySelfS0163"] = newOrderDetail.FEntrySelfS0163;
            
            drNewDtl_K3["FEntrySelfS0168"] = newOrderDetail.FEntrySelfS0168; 
            drNewDtl_K3["FEntrySelfS0171"] = newOrderDetail.FEntrySelfS0171;
            drNewDtl_K3["FMrpClosed"] = 0; 
            return true;
        }

        private bool UpdateSalesDetail( OrderDetail newOrderDetail, LogStatus updateMode)
        {

            return true;
        }

        

        private bool UpdateSales(DBAccess dbWebCon, DBAccess dbCon, string strKeyValue)
        {
            string strSQL = "select * from " + mstrOEHDR_Web + " where order_sn='" + strKeyValue + "'";
            DataRow drWebHdr = dbWebCon.GetDataFirstRow(strSQL);
            if (DelDetail(dbWebCon, dbCon, drWebHdr))
            {
                if (AddSalesDetail(dbWebCon, dbCon, drWebHdr))
                {
                    
                }
                else
                {
                    throw new MaxLeafException(strKeyValue + " 添加销售单失败.");
                    return false;
                }
            }
            else
            {
                return false;
            }
            return true;
        }

        private bool DelDetail(DBAccess dbWebCon, DBAccess dbCon, DataRow drWebHdr)
        {
            return true;
        }
    }
}
